<template>
    <div>
        <div id="qrcode" ref="qrcode" class="paywechat"></div>
    </div>
</template>
<script>
import QRCode from 'qrcode'
import { createOrderDY,orderPayWx,createGoodOrders,orderPayWxyx } from '@/api/pay.js'
export default {
    data() {
        return {
            codeurl: "",//回调url
            timer1: "", //支付循环
        }
    },
    mounted() {
        this.wechatpay()
    },
    methods: {
        //循环请求查看是否支付成功
        async wechatpay() {
            let obj = {
                price: this.paymoney,
                pay_type: 2,
            };
            try {
                //调用后端接口，接收返回url
                const res = await orderPayWxyx(obj);
                console.log(666666,res)
                //这句代码可以避免重复生成二维码
                document.getElementById("qrcode").innerHTML = "";
                this.codeurl = res.data.payDetail.code_url;
                //循环请求查看是否支付成功
                this.timer1 = setInterval(() => {
                    this.get_order_status(res.data.order_id);
                }, 1000);
                //如果在组件内的支付，很可能会监听不到组件销毁
                //通过$once来监听定时器，在beforeDestroy钩子可以被清除。
                this.$once("hook:beforeDestroy", () => {
                    clearInterval(timer1);
                    this.payshow = false;//支付的弹窗
                });
                //生成二维码
                this.$nextTick(() => {
                    this.qrcode = new QRCode("qrcode", {
                        width: 150, //二维码宽度
                        height: 150, //二维码高度
                        text: this.codeurl, //调用微信支付接口返回的微信特殊链接：例如"weixin://wxpay/bizpayurl?pr=uDKsQ4E00"
                        colorDark: "#000", //颜色配置
                        colorLight: "#fff",
                    });
                });
            } catch (err) {
                this.$message.error({
                    message: err,
                    type: "none",
                });
            }
        },

        //监听支付轮询
        async get_order_status(id) {
            try {
                const res = await get_order_status({ order_id: id });
                //如果支付成功
                if (res.data.order_status == 30) {
                    this.payshow = false;
                    clearInterval(this.timer1);
                    this.$message({
                        message: "支付成功",
                        type: "success",
                    });
                }
            } catch (err) {
                this.$message.error({
                    message: err,
                    type: "none",
                });
            }
        },
    }
}
</script>